//
//  RegisterTableView.m
//  乐清
//
//  Created by mac on 16/5/5.
//  Copyright © 2016年 Simon. All rights reserved.
//
// 0：自己填（一行）2：自己填（两行）  3：户籍省县 4：性别  5：民族  6：报名学校 7:是否政策照顾生 8：镇/村
#import "RegisterTableView.h"

@implementation RegisterTableView

- (void)dealloc {
    
    NSLog(@"%@被销毁了", self);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.dataSource = self;
        self.delegate = self;
        
        self.allowsSelection = NO;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.pageDataDic = [NSMutableDictionary dictionary];
        self.allDictionary = [NSMutableDictionary dictionary];
        
        [self addSwipeGestureRight];
    }
    return self;
}

- (void)setTableViewType:(NSInteger)tableViewType {
    
    _tableViewType = tableViewType;
    
    [self _setCellDataAndType];
    [self _createFooterView];
}

- (void)_setCellDataAndType {
    
    NSArray *childInfoArr = @[@"学生姓名",@"学生身份证号",@"学生户口所在地",@"性别",@"民族",@"报名学校",@"原就读幼儿园（非必填）",@"监护人移动电话",@"现居住地址"];
    NSArray *childPlaceholderArr = @[@"填写姓名",@"填写身份证号",@"省 市 区",@"请选择",@"请选择",@"请选择",@"填写原就读幼儿园",@"填写电话号码",@"填写现居住地址"];
    // 0：自己填  3：户籍省县 4：性别  5：民族  6：报名学校
    NSArray *childIsSelectArr = @[@0,@0,@3,@4,@5,@6,@2,@0,@0];
    
    NSMutableArray *childInfoMutableArr = [NSMutableArray arrayWithArray:childInfoArr];
    NSMutableArray *childPlaceholderMutableArr = [NSMutableArray arrayWithArray:childPlaceholderArr];
    NSMutableArray *childIsSelectMutableArr = [NSMutableArray arrayWithArray:childIsSelectArr];
    if (_tableViewType == 1) {
        [childInfoMutableArr addObject:@"房产地址"];
        [childInfoMutableArr addObject:@"房产证号"];
        [childInfoMutableArr addObject:@"是否政策照顾生（非必填）"];
        
        [childPlaceholderMutableArr addObject:@"如无本市房产，填0"];
        [childPlaceholderMutableArr addObject:@"无本市房产证，填0；在办理中，填1。"];
        [childPlaceholderMutableArr addObject:@"请选择"];
        
        [childIsSelectMutableArr addObject:@2];
        [childIsSelectMutableArr addObject:@2];
        [childIsSelectMutableArr addObject:@7];
    }
    if (_tableViewType == 11) {
        [childInfoMutableArr replaceObjectAtIndex:6 withObject:@"小学毕业学校（非必填）"];
        [childInfoMutableArr addObject:@"房产地址"];
        [childInfoMutableArr addObject:@"房产证号"];
        [childInfoMutableArr addObject:@"是否政策照顾生（非必填）"];
        
        [childPlaceholderMutableArr replaceObjectAtIndex:6 withObject:@"填写小学毕业学校"];
        [childPlaceholderMutableArr addObject:@"如无本市房产，填0"];
        [childPlaceholderMutableArr addObject:@"无本市房产证，填0；在办理中，填1。"];
        [childPlaceholderMutableArr addObject:@"请选择"];
        
        [childIsSelectMutableArr addObject:@2];
        [childIsSelectMutableArr addObject:@2];
        [childIsSelectMutableArr addObject:@7];
    }
    if (_tableViewType == 12) {
        [childInfoMutableArr replaceObjectAtIndex:6 withObject:@"小学毕业学校（非必填）"];
        [childPlaceholderMutableArr replaceObjectAtIndex:6 withObject:@"填写小学毕业学校"];
    }
    
    NSDictionary *childDic = @{
                               @"info"          : childInfoMutableArr,
                               @"type"          : childIsSelectMutableArr,
                               @"placeholder"   : childPlaceholderMutableArr
                               };
    
    NSArray *theGuardianInfoArr = @[@"第一监护人姓名",@"与学生的关系",@"第一监护人身份证号（非必填）",@"联系电话",@"工作单位（非必填）"];
    NSArray *theGuardianPlaceholderArr = @[@"填写姓名",@"填写双方关系",@"填写身份证号",@"填写电话号码",@"填写工作单位"];
    NSArray *theGuardianIsSelectArr = @[@0,@0,@2,@0,@0];
    NSDictionary *theGuardianDic = @{
                                     @"info"          : theGuardianInfoArr,
                                     @"type"          : theGuardianIsSelectArr,
                                     @"placeholder"   : theGuardianPlaceholderArr
                                     };
    
    
    NSArray *theSecondGuardianInfoArr = @[@"第二监护人姓名",@"与学生的关系",@"第二监护人身份证号（非必填）",@"联系电话",@"工作单位（非必填）"];
    NSArray *theSecondGuardianPlaceholderArr = @[@"填写姓名",@"填写双方关系",@"填写身份证号",@"填写电话号码",@"填写工作单位"];
    NSArray *theSecondGuardianIsSelectArr = @[@0,@0,@2,@0,@0];
    NSDictionary *theSecondGuardianDic = @{
                                           @"info"         : theSecondGuardianInfoArr,
                                           @"type"         : theSecondGuardianIsSelectArr,
                                           @"placeholder"  : theSecondGuardianPlaceholderArr
                                           };
    NSDictionary *allDic = @{
                             @"0" : childDic,
                             @"1" : theGuardianDic,
                             @"2" : theSecondGuardianDic
                             };
    _allDictionary = [NSMutableDictionary dictionaryWithDictionary:allDic];
}

- (void)_createFooterView {
    
    for (UIView *sub in self.tableFooterView.subviews) {
        //        NSLog(@"%@", sub);
        [sub removeFromSuperview];
    }
    //尾视图
    UIView *footView = [[UIView alloc] initWithFrame:CGRectZero];
    footView.frame = CGRectMake(0, 0, kScreenWidth, kFooterButtonHeight + kSpaceToSideCustom + 100 + kNavHeight);
    //下一步按钮
    UIButton *nextButton = [[UIButton alloc] initWithFrame:CGRectZero];
    
    nextButton.frame = CGRectMake(kSpaceToSideCustom, kSpaceToSideCustom * 1.5, kScreenWidth - 2 * kSpaceToSideCustom, kFooterButtonHeight);
    //    NSLog(@"%ld", (long)_currentPage);
    if (_currentPage < 2) {
        [nextButton setTitle:@"下一步" forState:UIControlStateNormal];
    } else {
        [nextButton setTitle:@"提交" forState:UIControlStateNormal];
    }
    nextButton.titleLabel.textColor = [UIColor whiteColor];
    nextButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    nextButton.backgroundColor = [UIColor greenColor];
    [nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self checkIfButtonIsShown:nextButton];
    [footView addSubview:nextButton];
    //如果需要显示注意（需知）
    if (!_currentPage) {
        
        NSString *labelText = [NSString string];
        //公办学校
        if (_tableViewType % 2 == 1) {
            labelText = @"注：\n学生必须年满六周岁\n房产地址：如本市无房产，填“0”。\n房产证号：无本市房产证，填“0”；在办理中，填“1”。";
        } else {
            labelText = @"注：\n学生必须年满六周岁";
        }
        CGFloat labelHeight = [UILabel heightWithText:labelText withFontSize:kFooterTextFont withWidth:kScreenWidth - 2 * kSpaceToSideCustom];
        
        //尾视图重新布局
        footView.frame = CGRectMake(0, 0, kScreenWidth, labelHeight + kFooterButtonHeight + 2 * kSpaceToSideCustom + 100 + kNavHeight);
        //下一步按钮重新布局
        nextButton.frame = CGRectMake(kSpaceToSideCustom, labelHeight + 3 * kSpaceToSideCustom, kScreenWidth - 2 * kSpaceToSideCustom, kFooterButtonHeight);
        //注意
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        
        noteLabel.text = labelText;
        noteLabel.textColor = [UIColor redColor];
        noteLabel.font = [UIFont systemFontOfSize:kFooterTextFont];
        noteLabel.numberOfLines = 0;
        noteLabel.frame = CGRectMake(kSpaceToSideCustom, kSpaceToSideCustom / 2, kScreenWidth - 2 * kSpaceToSideCustom, labelHeight);
        
        [footView addSubview:noteLabel];
        NSArray *buttonNames = @[@"点击查看学校报名情况",@"点击查看学校学区对应"];
        CGFloat buttonWidth = kFooterTextFont * [buttonNames[0] length];
        if (_tableViewType % 2 == 1) {
            for (int i = 0; i < 2; i++) {
                NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:buttonNames[i]];
                NSDictionary *attributedDic = @{
                                            NSUnderlineStyleAttributeName : [NSNumber numberWithInteger:NSUnderlineStyleSingle],
                                            NSUnderlineColorAttributeName : [UIColor blueColor],
                                            NSFontAttributeName : [UIFont systemFontOfSize:kFooterTextFont],
                                            NSForegroundColorAttributeName : [UIColor blueColor]
                                                };
                [attributedStr setAttributes:attributedDic range:NSMakeRange(0, [buttonNames[i] length])];
                
                UIButton *viewDetails = [[UIButton alloc] initWithFrame:CGRectMake(kSpaceToSideCustom + i * (buttonWidth + kSpaceToSideCustom), noteLabel.bottom, buttonWidth, kFooterTextFont)];
                [viewDetails setAttributedTitle:attributedStr forState:UIControlStateNormal];
                viewDetails.tag = 300 + i + _tableViewType;
                [viewDetails addTarget:self action:@selector(viewMoreAboutSchool:) forControlEvents:UIControlEventTouchUpInside];
                [footView addSubview:viewDetails];
            }
        } else {
            NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:buttonNames[0]];
            NSDictionary *attributedDic = @{
                                            NSUnderlineStyleAttributeName : [NSNumber numberWithInteger:NSUnderlineStyleSingle],
                                            NSUnderlineColorAttributeName : [UIColor blueColor],
                                            NSFontAttributeName : [UIFont systemFontOfSize:kFooterTextFont],
                                            NSForegroundColorAttributeName : [UIColor blueColor]
                                            };
            [attributedStr setAttributes:attributedDic range:NSMakeRange(0, [buttonNames[0] length])];
            
            UIButton *viewDetails = [[UIButton alloc] initWithFrame:CGRectMake(kSpaceToSideCustom, noteLabel.bottom, buttonWidth, kFooterTextFont)];
            [viewDetails setAttributedTitle:attributedStr forState:UIControlStateNormal];
            viewDetails.tag = 321 + _tableViewType;
            [viewDetails addTarget:self action:@selector(viewMoreAboutSchool:) forControlEvents:UIControlEventTouchUpInside];
            [footView addSubview:viewDetails];

        }
    }
    
    self.tableFooterView = footView;
}

#pragma -mark -数据存储与删除
- (void)setModelData {
    
}

- (void)deleteModelDataForPage:(NSInteger)page {
    
}

#pragma -mark -右滑手势
- (void)addSwipeGestureRight {
    
    _swipeBack = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(slipToRight:)];
    
    [self addGestureRecognizer:_swipeBack];
}

- (void)slipToRight:(UISwipeGestureRecognizer *)sender {
    
    if ((sender.direction == UISwipeGestureRecognizerDirectionRight)&&(_currentPage > 0)) {
        
        _currentPage --;
        if (_pageChangedBlock) {
            self.pageChangedBlock((int)_currentPage);
        }
        
        _pageDataDic = [NSMutableDictionary dictionary];
        [self deleteModelDataForPage:(_currentPage + 1)];
        [self scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        [self reloadData];
        
        [self _createFooterView];
    }
}

//移除右滑返回手势
- (void)removeSwipeBackGesture {
    if (self.swipeBack) {
        [self removeGestureRecognizer:self.swipeBack];
    }
}

#pragma -mark -判断是否按钮已经出现 
- (void)checkIfButtonIsShown:(UIButton *)sender {

    if (self.contentSize.height) {
        if (_buttonIsShownBlock) {
            self.buttonIsShownBlock(1);
        }
    }
    
}
#pragma -mark -增删cell
- (void)addOneCell:(NSInteger)row withTitle:(NSString *)name withType:(NSNumber *)type withPlaceHolder:(NSString *)placeHolder {
    
    [self beginUpdates];
    
    NSString *key = [NSString stringWithFormat:@"%ld", (long)_currentPage];
    NSMutableDictionary *personDic = [NSMutableDictionary dictionaryWithDictionary:_allDictionary[key]];
    
    NSMutableArray *infoArr = [NSMutableArray arrayWithArray:[personDic objectForKey:@"info"]];
    NSMutableArray *isSelectArr = [NSMutableArray arrayWithArray:[personDic objectForKey:@"type"]];
    NSMutableArray *placeholderArr = [NSMutableArray arrayWithArray:[personDic objectForKey:@"placeholder"]];
    
    [infoArr insertObject:name atIndex:row];
    [isSelectArr insertObject:type atIndex:row];
    [placeholderArr insertObject:placeHolder atIndex:row];
    
    [personDic setValue:infoArr forKey:@"info"];
    [personDic setValue:isSelectArr forKey:@"type"];
    [personDic setValue:placeholderArr forKey:@"placeholder"];
    
    [_allDictionary setValue:personDic forKey:key];
    
    NSArray *_tempIndexPathArr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0]];
    [self insertRowsAtIndexPaths:_tempIndexPathArr withRowAnimation:UITableViewRowAnimationNone];
    
    [self endUpdates];
}

- (void)removeOneCell:(NSInteger)row {
    
    [self beginUpdates];
    
    NSString *key = [NSString stringWithFormat:@"%ld", (long)_currentPage];
    NSMutableDictionary *personDic = [NSMutableDictionary dictionaryWithDictionary:_allDictionary[key]];
    
    NSMutableArray *infoArr = [NSMutableArray arrayWithArray:[personDic objectForKey:@"info"]];
    NSMutableArray *isSelectArr = [NSMutableArray arrayWithArray:[personDic objectForKey:@"type"]];
    NSMutableArray *placeholderArr = [NSMutableArray arrayWithArray:[personDic objectForKey:@"placeholder"]];
    
    [infoArr removeObjectAtIndex:row - 1];
    [isSelectArr removeObjectAtIndex:row - 1];
    [placeholderArr removeObjectAtIndex:row - 1];
    
    [personDic setValue:infoArr forKey:@"info"];
    [personDic setValue:isSelectArr forKey:@"type"];
    [personDic setValue:placeholderArr forKey:@"placeholder"];
    
    [_allDictionary setValue:personDic forKey:key];
    
    NSArray *_tempIndexPathArr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:row inSection:0]];
    [self deleteRowsAtIndexPaths:_tempIndexPathArr withRowAnimation:UITableViewRowAnimationFade];
    
    [self endUpdates];
}

#pragma -mark -按钮点击
- (void)nextButtonAction:(UIButton *)sender {
    
    [self endEditing:YES];
    if (_currentPage < 2) {
        _currentPage ++;
        if (_pageChangedBlock) {
            self.pageChangedBlock((int)_currentPage);
        }
        
        _pageDataDic = [NSMutableDictionary dictionary];
        [self scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
        [self reloadData];

        [self _createFooterView];
    } else {
        
        [self submitData];
    }
    
}

- (void)submitData {
    
}

- (void)viewMoreAboutSchool:(UIButton *)sender {
    
    if (sender.tag % 2 == 1) {
        NSLog(@"view more about school");
    } else {
        NSLog(@"view more about corresponding content");
    }
    
}

#pragma -mark -touch event
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //    NSLog(@"%@ touchs began", [self class]);
    UITouch *touch = [touches anyObject];
    CGPoint p = [touch locationInView:self];
    
    NSInteger selectViewExit = 0;
    for (UIView *aSubView in self.subviews) {
        
        if ([aSubView isKindOfClass:[SelectView class]]) {

            selectViewExit++;
 
            if (![aSubView pointInside:p withEvent:event]) {
                
                [aSubView removeFromSuperview];
                [self endEditing:YES];
                
            } else if (p.y < aSubView.frame.origin.y) {
                
                [aSubView removeFromSuperview];
                [self endEditing:YES];
                
            } else {
                //                NSLog(@"in");
            }
        }
    }
    
    if (!selectViewExit) {
        
        [self endEditing:YES];
    }
}

#pragma -mark -scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGRect frame = self.frame;
    CGPoint contentOffsetPoint = self.contentOffset;
//    NSLog(@"contentOffsetPoint.y = %f", contentOffsetPoint.y);
//    NSLog(@" -- = %f", self.contentSize.height - frame.size.height);
    if (contentOffsetPoint.y - (self.contentSize.height - frame.size.height) > -20) {
//        NSLog(@"scroll to bottom");
        if (_scrollToBottomBlock) {
            self.scrollToBottomBlock(1);
        }
    }
}

#pragma -mark -UITableView delegate
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    NSArray *titleArr = @[@"学生基本信息",@"第一监护人信息",@"第二监护人信息"];
    NSMutableString *title = [NSMutableString string];
    if (_currentPage < 3) {
        title = titleArr[_currentPage];
    } else {
        title = titleArr[_currentPage - 2];
    }
    
    return title;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 0) {
        
        NSString *key = [NSString stringWithFormat:@"%ld", (long)_currentPage];
        NSDictionary *personDic = _allDictionary[key];
        NSArray *infoArr = [personDic objectForKey:@"info"];
        NSInteger num = (NSInteger)infoArr.count;
        
        return num;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *key = [NSString stringWithFormat:@"%ld", (long)_currentPage];
    NSDictionary *personDic = _allDictionary[key];
    NSArray *typeArr = [personDic objectForKey:@"type"];
    
    if ([typeArr[indexPath.row] integerValue] == 2) {
        return kCellHeight * 2;
    }
    return kCellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _tableViewCell = [[RegisterTableViewCell alloc] init];
    
    return _tableViewCell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //    NSLog(@"cell %ld", (long)_currentPage);
    NSString *key = [NSString stringWithFormat:@"%ld", (long)_currentPage];
    NSDictionary *personDic = _allDictionary[key];
    
    NSArray *infoArr = [personDic objectForKey:@"info"];
    NSArray *isSelectArr = [personDic objectForKey:@"type"];
    NSArray *placeholderArr = [personDic objectForKey:@"placeholder"];
    
    NSDictionary *infoDic = @{
                              @"info"        : infoArr[indexPath.row],
                              @"type"        : isSelectArr[indexPath.row],
                              @"placeholder" : placeholderArr[indexPath.row]
                              };
    
    ((RegisterTableViewCell *)cell).layoutDic = infoDic;
    
    //回调
    __weak RegisterTableView *weakSelf = self;
    weakSelf.tableViewCell.transformUpBlock = ^(double timeInterval, float offset) {
        [UIView animateWithDuration:timeInterval animations:^{
            
            tableView.transform = CGAffineTransformMakeTranslation(0, -offset);
        }];
    };
    
    weakSelf.tableViewCell.transformDownBlock = ^(double timeInterval) {
        
        [UIView animateWithDuration:timeInterval animations:^{
            
            tableView.transform = CGAffineTransformIdentity;
        }];
    };
    
    weakSelf.tableViewCell.selectViewShouldRemoveBlock = ^(int textFieldExit) {
        if (textFieldExit) {
            for (UIView *aSubView in weakSelf.subviews) {
                if ([aSubView isKindOfClass:[SelectView class]]) {
                    [aSubView removeFromSuperview];
                }
            }
        } else {
            [weakSelf endEditing:YES];
        }
    };
    
    weakSelf.tableViewCell.editingEnd = ^(NSString *key, NSString *value) {
//        NSString *allDicKey = [NSString stringWithFormat:@"%ld", (long)weakSelf.currentPage];
//        NSDictionary *personDic = weakSelf.allDictionary[allDicKey];
//        NSArray *infoArr = [personDic objectForKey:@"info"];
        
        if ([key isEqualToString:@"学生户口所在地"]) {
            if ([value containsString:@"非"]) {
                if ([weakSelf.pageDataDic[@"学生户口所在地"] isEqualToString:@"乐清市户籍"]) {
                    [weakSelf.pageDataDic removeObjectForKey:@"社区/村"];
                    [weakSelf removeOneCell:4];
                    [weakSelf.pageDataDic removeObjectForKey:@"镇/区"];
                    [weakSelf removeOneCell:3];
                }
            } else {
                if ([weakSelf.pageDataDic[@"学生户口所在地"] isEqualToString:@"乐清市户籍"]) {
                    [weakSelf.pageDataDic removeObjectForKey:@"社区/村"];
                    [weakSelf removeOneCell:4];
                    [weakSelf.pageDataDic removeObjectForKey:@"镇/区"];
                    [weakSelf removeOneCell:3];
                }
                [weakSelf addOneCell:3 withTitle:@"镇/区" withType:@8 withPlaceHolder:@"请选择"];
                [weakSelf addOneCell:4 withTitle:@"社区/村" withType:@0 withPlaceHolder:@"请填写社区或村地址"];
            }
        }
        [weakSelf.pageDataDic setValue:value forKey:key];
    };
}

@end
